package com.zhieasy.common.util;

import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.domain.proto.storage.DownloadByteArray;
import com.github.tobato.fastdfs.domain.proto.storage.DownloadCallback;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.zhieasy.common.exception.Asserts;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;

/**
 * 文件操作工具
 * @author 风亦未止
 * @date 2021/11/22 9:10
 */
@Slf4j
@Component
public class FilesUtil {
    @Resource
    private FastFileStorageClient storageClient;

    /**
     * 文件上传
     * @param multipartFile
     * @return
     * @throws Exception
     */
    public String upload(MultipartFile multipartFile) throws Exception {
        //获取文件后缀
        String originalFilename = multipartFile.getOriginalFilename().substring(multipartFile.getOriginalFilename().lastIndexOf(".") + 1);
        //上传
        StorePath storePath = this.storageClient.uploadFile(multipartFile.getInputStream(), multipartFile.getSize(), originalFilename, null);
        return storePath.getFullPath();
    }

    /**
     * 删除文件
     * @param fileUrl
     */
    public void deleteFile(String fileUrl) {
        if (StringUtils.isEmpty(fileUrl)) {
            Asserts.fail("文件路径为空...");
            return;
        }
        try {
            StorePath storePath = StorePath.parseFromUrl(fileUrl);
            storageClient.deleteFile(storePath.getGroup(), storePath.getPath());
        } catch (Exception e) {
            log.info(e.getMessage());
            Asserts.fail(e.getMessage());
        }
    }

    /**
     * 文件下载
     * @param fileUrl
     * @return
     */
    public  byte[] downloadFile(String fileUrl){
        if (StringUtils.isEmpty(fileUrl)) {
            Asserts.fail("文件路径为空...");
        }
        DownloadCallback<byte[]> downloadCallback=new DownloadByteArray();
        byte[] bytes = new byte[1024 * 10];
        try {
            StorePath storePath = StorePath.parseFromUrl(fileUrl);
            bytes = storageClient.downloadFile(storePath.getGroup(), storePath.getPath(), downloadCallback);
        } catch (Exception e) {
            log.info(e.getMessage());
            Asserts.fail(e.getMessage());
        }
        return bytes;
    }
}
